/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * formMaquinas.java
 *
 * Created on 26/08/2011, 20:30:04
 */
package javalee.forms;

import javalee.maps.Maquina;
import java.util.ArrayList;
import java.util.Iterator;
import javalee.util.Uteis;
import javalee.dao.*;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author will
 */
public class formMaquinas extends javax.swing.JFrame {

    private maquinaDAO maqDAO;

    /** Creates new form formMaquinas */
    public formMaquinas() {
        initComponents();
        maqDAO = new maquinaDAO();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnOk = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        txtMaquina = new javax.swing.JTextField();
        lblMaquina = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        tbConsulta = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        txtConsulta = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        btnDelete = new javax.swing.JButton();
        txtId = new javax.swing.JTextField();
        lblId = new javax.swing.JLabel();
        btnNovo = new javax.swing.JButton();

        setTitle("Formulario de Maquinas");
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
            }
        });
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        btnOk.setText("Salvar");
        btnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOkActionPerformed(evt);
            }
        });

        btnCancelar.setText("Fechar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        txtMaquina.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtMaquinaActionPerformed(evt);
            }
        });
        txtMaquina.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtMaquinaKeyTyped(evt);
            }
        });

        lblMaquina.setText("Nome da máquina");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        tbConsulta.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Máquina"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbConsulta.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbConsultaMouseClicked(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                tbConsultaMouseReleased(evt);
            }
        });
        jScrollPane2.setViewportView(tbConsulta);

        jLabel2.setText("Nome da Máquina:");

        txtConsulta.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                txtConsultaMouseReleased(evt);
            }
        });
        txtConsulta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtConsultaActionPerformed(evt);
            }
        });
        txtConsulta.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtConsultaKeyReleased(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel3.setText("Pesquisar máquina");

        btnDelete.setText("Excluir");
        btnDelete.setEnabled(false);
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        txtId.setEditable(false);
        txtId.setEnabled(false);
        txtId.setFocusable(false);

        lblId.setText("ID:");

        btnNovo.setText("Limpar dados");
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblMaquina)
                    .addComponent(lblId))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtMaquina, javax.swing.GroupLayout.DEFAULT_SIZE, 451, Short.MAX_VALUE)
                        .addGap(6, 6, 6)
                        .addComponent(btnOk)
                        .addGap(66, 66, 66))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 409, Short.MAX_VALUE)
                                .addComponent(btnDelete))
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnNovo)))
                        .addGap(54, 54, 54))))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(364, Short.MAX_VALUE)
                .addComponent(jLabel3)
                .addGap(192, 192, 192))
            .addGroup(layout.createSequentialGroup()
                .addGap(268, 268, 268)
                .addComponent(btnCancelar)
                .addContainerGap(352, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 364, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtConsulta, javax.swing.GroupLayout.DEFAULT_SIZE, 503, Short.MAX_VALUE)))
                .addGap(60, 60, 60))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(45, 45, 45)
                .addComponent(jLabel3)
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtConsulta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnDelete)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 48, Short.MAX_VALUE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(lblId)
                        .addComponent(btnNovo)))
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtMaquina, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblMaquina)
                    .addComponent(btnOk))
                .addGap(18, 18, 18)
                .addComponent(btnCancelar)
                .addContainerGap())
        );

        lblId.getAccessibleContext().setAccessibleName("ID");

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed

    if(ValidarForm())
    {
    
    try {
        int row = tbConsulta.getSelectedRow();
        boolean sucesso = false;
        
        Maquina maqNova = new Maquina();
        if(row == -1){
            maqNova.setDescricao(txtMaquina.getText());
            if (maqDAO.cadastrar(maqNova)) {
                JOptionPane.showMessageDialog(null, "Máquina cadastrada.");
                txtMaquina.setText("");
            } else {
                JOptionPane.showMessageDialog(null, "Problema ao cadastrar máquina.");
            }
        }else{
            maqNova.setId(Integer.parseInt(txtId.getText()));
            maqNova.setDescricao(txtMaquina.getText());
            if (maqDAO.alterar(maqNova)) {
                JOptionPane.showMessageDialog(null, "Máquina alterada.");
            } else {
                JOptionPane.showMessageDialog(null, "Problema ao alterar máquina.");
            }
        }

        //maqDAO.cadastrar(maqNova);
        

    } catch (Exception e) {
        System.out.println(e.toString());
    }
    }
}//GEN-LAST:event_btnOkActionPerformed

private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
// TODO add your handling code her
    setVisible(false);
}//GEN-LAST:event_formWindowClosed

private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
// TODO add your handling code here:
    try {
        formWindowClosed(null);
    } catch (Exception e) {
    }
}//GEN-LAST:event_btnCancelarActionPerformed

private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
    if (tbConsulta.getSelectedRow() == -1){
        JOptionPane.showMessageDialog(null, "Selecione uma máquina.");
        btnDelete.setEnabled(false);
    }
    else{
    int row = tbConsulta.getSelectedRow();
    
    DefaultTableModel tableModel = (DefaultTableModel)tbConsulta.getModel();  
    Maquina maqEx = new Maquina(Integer.parseInt(tableModel.getValueAt(row, 0).toString()));
    
    if(JOptionPane.showConfirmDialog(null, "Tem certeza que deseja excluir a máquina?","Confirmação!",JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION){
        if( maqDAO.excluir(maqEx) ){
            JOptionPane.showMessageDialog(null, "Máquina excluída com sucesso.");
            btnDelete.setEnabled(false);
            txtConsulta.setText("");
        } else {
            JOptionPane.showMessageDialog(null, "Problema ao excluir máquina.");
        }
        
    }
    limpaDados();
    preencheDados();
    }
}//GEN-LAST:event_btnDeleteActionPerformed

private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
    preencheDados();
}//GEN-LAST:event_formWindowOpened

private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
    preencheDados();
}//GEN-LAST:event_formWindowGainedFocus

private void tbConsultaMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbConsultaMouseReleased
    int row = tbConsulta.getSelectedRow();
    
    DefaultTableModel tableModel = (DefaultTableModel)tbConsulta.getModel();  
    txtId.setText(tableModel.getValueAt(row, 0).toString());
    txtMaquina.setText(tableModel.getValueAt(row, 1).toString());
}//GEN-LAST:event_tbConsultaMouseReleased

private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
    tbConsulta.clearSelection();
    limpaDados();
}//GEN-LAST:event_btnNovoActionPerformed

private void txtConsultaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtConsultaKeyReleased
    if(evt.getKeyCode()==10){
        preencheDados();
    }
}//GEN-LAST:event_txtConsultaKeyReleased

private void txtConsultaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtConsultaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtConsultaActionPerformed

private void txtConsultaMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtConsultaMouseReleased
// TODO add your handling code here:
}//GEN-LAST:event_txtConsultaMouseReleased

private void txtMaquinaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMaquinaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtMaquinaActionPerformed

private void txtMaquinaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMaquinaKeyTyped
    if(txtMaquina.getText().length() > 45){
        txtMaquina.setText(txtMaquina.getText().substring(0, 45));
    }
}//GEN-LAST:event_txtMaquinaKeyTyped

private void tbConsultaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbConsultaMouseClicked
    btnDelete.setEnabled(true);
    // TODO add your handling code here:
}//GEN-LAST:event_tbConsultaMouseClicked

private void preencheDados(){
    if(!Uteis.validaCampoTexto(txtConsulta)){
            JOptionPane.showMessageDialog(null,"Campo de pesquisa está incorreto.");
        }
        else{
     //Trago a lista de maquinas do banco
     ArrayList<Maquina> lista = maqDAO.consultar(txtConsulta.getText().toString());
     tbConsulta.removeAll();
     
     //Pego o TableModel do componente JTable
     DefaultTableModel tableModel = (DefaultTableModel)tbConsulta.getModel();  
     //Limpo os dados do componente
     tableModel.setNumRows(0);
     
     //Passo pela lista de Maquinas, inserindo no JTable
     for(Iterator<Maquina> it = lista.iterator(); it.hasNext();){
        Maquina c = (Maquina)it.next();
        tableModel.addRow(new Object[]{
            c.getId(),//Cada campo que coloco vira uma coluna
            c.getDescricao()
        });     
    }   
}
}

private void limpaDados(){
    txtId.setText("");
    txtMaquina.setText("");
}
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(formMaquinas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(formMaquinas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(formMaquinas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(formMaquinas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new formMaquinas().setVisible(true);
            }
        });
    }
    
    private boolean ValidarForm()
    {
        boolean valido = true;
        
        if(txtMaquina.getText().length()<=3)
        {
            valido = false;
            JOptionPane.showMessageDialog(null,"Nome da máquina inválido.");
        }
         else if(!Uteis.validaCampoTexto(txtMaquina)){
            valido = false;
            JOptionPane.showMessageDialog(null,"Nome da máquina inválido.");
        }
        return valido;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnOk;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel lblId;
    private javax.swing.JLabel lblMaquina;
    private javax.swing.JTable tbConsulta;
    private javax.swing.JTextField txtConsulta;
    private javax.swing.JTextField txtId;
    private javax.swing.JTextField txtMaquina;
    // End of variables declaration//GEN-END:variables
}
